import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

//通过 FileChannel 将给定路径下 文件 复制到指定文件下
public class FileChannelDemo02 {
    private static final int MAX_SIZE = 1024;
    public static void main(String[] args) throws IOException {
        RandomAccessFile srcFile = new RandomAccessFile("D:\\JavaLearn\\idea\\Code\\JavaSE_Code\\MyNet\\src\\tmp\\nio.txt", "rw");
        FileChannel srcChannel = srcFile.getChannel();
        ByteBuffer buffer =  ByteBuffer.allocate(MAX_SIZE);

        RandomAccessFile desFile = new RandomAccessFile("D:\\JavaLearn\\idea\\Code\\JavaSE_Code\\MyNet\\src\\tmp\\nio_cp.txt", "rw");
        FileChannel desChannel = desFile.getChannel();
        //int len;
       // while((len = srcChannel.read(buffer))!= -1){   //将数据从srcChannel读入buffer -> 切换buffer模式 -> 将数据从buffer写入desChannel
            while(( srcChannel.read(buffer))!= -1){
//            byte[] bys = new byte[len];
//            for(int i = 0; i < len; i++)
//                bys[i] = readbuffer.get(i);
            buffer.flip();  // 写模式切换为读模式
            while(buffer.hasRemaining()){
                desChannel.write(buffer);
            }
            buffer.clear();
        }
            srcFile.close();
            desFile.close();
    }
}
